//
//  LZCouponPublishedTableView.m
//  laziz_Merchant
//
//  Created by xbnzd on 16/12/19.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZPublishedCouponTableView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LZPublisedCouponCell.h"
#import "LZCouponPresenter.h"
#import "LZCouponListModel.h"
#import "LZCouponListCellPresenter.h"
#import "LZCouponListCellDelegatePresenter.h"
#import "LZPlayVideoManager.h"
#import "UITableView+LZTableView.h"

@interface LZPublishedCouponTableView()<UITableViewDataSource,UITableViewDelegate,LZCouponListCellDelegate,LZPublishCellDelegate,LZPlayVideoManagerDelegate>
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSTimeInterval timeStamp;
@property (nonatomic, strong) LZCouponPresenter *couponPresenter;
@property (nonatomic, strong) LZCouponListCellPresenter *couponListCellPresenter;
@end

@implementation LZPublishedCouponTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.delegate = self;
        self.dataSource = self;
        _currentPage = 1;
        _dataArr = @[].mutableCopy;
        _couponPresenter = [[LZCouponPresenter alloc] init];
        _couponListCellPresenter  = [[LZCouponListCellPresenter alloc] init];
        [self registerCell];
        [self addHeaderRefresh];
        [self addFooterRefresh];
    }
    
    return self;
}
#pragma mark -
#pragma mark private
- (void)registerCell
{
    [self registerNib:[UINib nibWithNibName:@"LZPublisedCouponCell" bundle:nil] forCellReuseIdentifier:@"publiccell"];
}
- (void)checkHaveData
{
    [LZPlayVideoManager shareManager].playVideoManagerDelegate = self;
    if (_dataArr.count == 0) {
        [self.mj_header beginRefreshing];
    }
}

- (void)downLoadNewData
{
    [self getPublishedDataWithPage:1 isDown:YES];
}

- (void)upLoadMoreData
{
    [self getPublishedDataWithPage:self.currentPage isDown:NO];
}

- (void)getPublishedDataWithPage:(NSInteger)cPage isDown:(BOOL)isDown
{
    WS(wSelf);
    [self.couponPresenter getCouponListWithSellerID:self.sellerId CouponState:[NSString stringWithFormat:@"%ld",self.couponListCode - 1000] CouponName:nil Cpage:cPage Limit:10 ResultSuccess:^(NSArray *listArr, NSInteger totalPage, NSInteger currentPage, NSTimeInterval timeStamp) {
        
        if (isDown) {
            if (wSelf.mj_footer.state == MJRefreshStateNoMoreData) {
                wSelf.mj_footer.state = MJRefreshStateIdle;
            }
            if (totalPage == 0) {
                [wSelf setNoDataFooterText];
                [wSelf.mj_footer endRefreshingWithNoMoreData];
            }
            if (wSelf.dataArr.count > 0) {
                [wSelf.dataArr removeAllObjects];
            }
            [wSelf.dataArr addObjectsFromArray:listArr];
            wSelf.currentPage = currentPage + 1;
            [wSelf.mj_header endRefreshing];
            
        }else{
            if (currentPage == wSelf.currentPage) {
                if (wSelf.currentPage < totalPage) {
                    [wSelf.mj_footer endRefreshing];
                }else{
                    [wSelf setNoMoreDataFooterText];
                    [wSelf.mj_footer endRefreshingWithNoMoreData];
                }
                wSelf.currentPage ++;
                [wSelf.dataArr addObjectsFromArray:listArr];
            }
        }
        
        [wSelf reloadData];
        
        if (isDown && self.dataArr.count>0) {
            //默认播放第一个视频
            self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
                
            }];
        }
        
    } Failure:^(NSString *fail) {
        [wSelf.mj_header endRefreshing];
        [wSelf.mj_footer endRefreshing];
    }];

}

#pragma mark -
#pragma mark tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(wSelf);
    return [tableView fd_heightForCellWithIdentifier:@"publiccell" cacheByIndexPath:indexPath configuration:^(id cell) {
        LZPublisedCouponCell *cellTemp = (LZPublisedCouponCell *)cell;
        if (wSelf.dataArr.count > 0) {
            LZCouponListModel *m = wSelf.dataArr[indexPath.row];
            [cellTemp loadContentWithModel:m indexPath:indexPath];
        }
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZPublisedCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:@"publiccell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.cellClickDelegate = self;
    cell.publishCellDelegate = self;
    if (self.dataArr.count > 0) {
        LZCouponListModel *m = self.dataArr[indexPath.row];
        [cell loadContentWithModel:m indexPath:indexPath];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!decelerate && self.isCurrentShowingTable){//缓慢拖动.手指离开时
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
            
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.isCurrentShowingTable) {
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
            
        }];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滑动时判断当前播放的cell是否已经离开屏幕.已经离开,停止播放
    [[LZPlayVideoManager shareManager] removePlayViewWhenTableViewDidScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath];
}

#pragma mark -
#pragma mark cell delegate

/**
 点击 删除 提交 按钮协议方法
 
 @param index <#index description#>
 @param tableViewCell <#cellIndexPath description#>
 */
- (void)clickCellButtonWithIndex:(CouponListEventCode)index andCell:(id)tableViewCell
{
    [self releasePlayViewRAM];
    LZPublisedCouponCell *cellTemp = (LZPublisedCouponCell *)tableViewCell;
    NSIndexPath *indexP = [self indexPathForCell:cellTemp];
    LZCouponListModel *modelTemp = self.dataArr[indexP.row];
    
    WS(wSelf);
    [self.couponListCellPresenter dealClickCouponOperationButtonCode:index andModel:modelTemp isInCouponDetailVC:NO operationSuccess:^{
        
        [wSelf.dataArr removeObjectAtIndex:indexP.row];
        [wSelf beginUpdates];
        [wSelf deleteRowsAtIndexPaths:@[indexP] withRowAnimation:UITableViewRowAnimationFade];
        [wSelf endUpdates];
        
        //同时,协议通知最上层vc,操作成功,更新数组
        if (wSelf.publishTableDelegate && [self.publishTableDelegate respondsToSelector:@selector(publishCellClickBtnSuccessToRefeshSuperVCTitleCount)]) {
            [wSelf.publishTableDelegate publishCellClickBtnSuccessToRefeshSuperVCTitleCount];
        }
        
    } Failure:^(NSString *error) {
        
    }];
}


/**
 点击
 
 @param indexPath <#indexPath description#>
 @param eventCode <#eventCode description#>
 */
- (void)clickDetailOrPlayVideoBtnWithIndexPath:(NSIndexPath *)indexPath couponBtnCode:(CouponListEventCode)eventCode withCell:(id)cell
{
    [self releasePlayViewRAM];
    LZPublisedCouponCell *cellTemp = (LZPublisedCouponCell *)cell;
    NSIndexPath *indexP = [self indexPathForCell:cellTemp];
    LZCouponListModel *modelTemp = self.dataArr[indexP.row];
    
    WS(wSelf);
    if (eventCode == kCouponList_playVideo) {
        DLog(@"播放视频");
        [UIView animateWithDuration:0.3 animations:^{
            [wSelf scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
        } completion:^(BOOL finished) {
            wSelf.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenClickVideoCoverImgWithIndexPath:indexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
                
            }];
        }];
    }else{
        if (self.publishTableDelegate && [self.publishTableDelegate respondsToSelector:@selector(publishCellClickDetailBtnWithModel:couponEventCode: operationSuccess:)]) {
   
            [self.publishTableDelegate publishCellClickDetailBtnWithModel:modelTemp couponEventCode:eventCode operationSuccess:^(CouponListEventCode returnEventCode, LZCouponListModel *returnModel) {
                
                if (returnEventCode == kCouponList_finish) {
                    [wSelf.dataArr removeObjectAtIndex:indexP.row];
                    [wSelf beginUpdates];
                    [wSelf deleteRowsAtIndexPaths:@[indexP] withRowAnimation:UITableViewRowAnimationFade];
                    [wSelf endUpdates];
                }
            }];
        }
    }
    
}

#pragma mark -
#pragma mark  播放控制器获取资源delegate
- (NSString *)playVideoManagerGetVideoUrlWith:(NSIndexPath *)cellIndexPath
{
    LZCouponListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoUrl;
}

- (UIView *)playVidewManagerGetPlayBackgroundViewWith:(NSIndexPath *)cellIndexPath
{
    LZPublisedCouponCell *cell = [self cellForRowAtIndexPath:cellIndexPath];
    
    return cell.playBgView;
}

@end
